package inet.app.vod.activity.film;

import inet.app.vod.activity.R;
import inet.app.vod.activity.common.BaseActivity;
import inet.app.vod.adapter.FilmCommonAdapter;
import inet.app.vod.adapter.SlideImagesAdapter;
import inet.app.vod.config.AppConstants;
import inet.app.vod.db.DaoCategory;
import inet.app.vod.db.DaoFactory;
import inet.app.vod.listeners.SelectCategoryVideoListener;
import inet.app.vod.listeners.SlideImageClickListener;
import inet.app.vod.listeners.VideoSummaryListener;
import inet.app.vod.net.http.VolleyClient;
import inet.app.vod.net.http.VolleyListener;
import inet.app.vod.object.CategoryModel;
import inet.app.vod.object.FilmCommonModel;
import inet.app.vod.object.MovieModel;
import inet.app.vod.object.ResultJsonModel;
import inet.app.vod.object.SlideObject;
import inet.app.vod.parser.Parse;
import inet.app.vod.util.MyUtil;
import inet.app.vod.view.MyViewPagerIndicator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.inet.app.framework.bitmap.BitmapUtil;
import com.inet.app.framework.intentutil.LaunchIntent;
import com.inet.app.framework.util.Log;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

public class IPhimActivity extends BaseActivity implements
		VideoSummaryListener, SelectCategoryVideoListener {

	private int NUM_MOVIE_HOTS = 3;
	private ViewPager mSlideImages;
	private MyViewPagerIndicator mIndicators;
	private ListView mFilmListView;
	private FilmCommonAdapter mAdapter;
	private RelativeLayout mSlideLayout;

	private DaoCategory mDaoCategory;
	private SlideImagesAdapter mSlideAdapters;
	private List<FilmCommonModel> mFilmCommonModels = new ArrayList<FilmCommonModel>();
	private List<CategoryModel> mCategories = new ArrayList<CategoryModel>();
	private List<MovieModel> mMovieHots = new ArrayList<MovieModel>();
	private FilmCommonModel mFilmCommonModel;
	private String mHomeId = AppConstants.ID_IPHIM;

	private int mSizeCategories = 0;
	private int mIteCategories = 0;

	private SlideImageClickListener onSlideListener = new SlideImageClickListener() {

		@Override
		public void onSlideClick(SlideObject slide) {
			MovieModel movie = (MovieModel) slide;
			Bundle bundle = new Bundle();
			bundle.putSerializable("movie", movie);
			bundle.putString("home_id", mHomeId);
			LaunchIntent.start(IPhimActivity.this, IPhimDetailActivity.class,
					bundle);
		}
	};

	private void initModels() {

		mDaoCategory = DaoFactory.getInstance(getApplicationContext())
				.getDaoCategory();

		/* Get type film/video from bundle */
		Bundle bundle = getIntent().getExtras();
		if (null != bundle) {
			mHomeId = bundle.getString("home_id");
		}

		// copy logo app to sdcard to share facebook
		try {
			BitmapUtil.writeBitmapFromDrawable(this, R.drawable.img_logo,
					AppConstants.LOGO);
		} catch (IOException e) {
			Log.e("don't copy logo to sdcard " + e.toString());
		}

	}

	private void initViews() {
		mFilmListView = (ListView) findViewById(R.id.film_listview);
		mSlideLayout = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.header_slide_images, null);
		mIndicators = (MyViewPagerIndicator) mSlideLayout
				.findViewById(R.id.my_indicator);
		mIndicators.setColorDefault(Color.WHITE);
		mFilmListView.addHeaderView(mSlideLayout);
		setTitle(mHomeId.equals(AppConstants.ID_ICLIP) ? AppConstants.NAME_ICLIP
				: AppConstants.NAME_IPHIM);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_iphim);
		initUIBase();
		initModels();
		initViews();
		requestCategories();
	}

	private void requestCategories() {
		// get categories from database
		mCategories = mDaoCategory.selectCategoryFromGroup(mHomeId);
		if (mCategories != null && mCategories.size() > 0) {
			showCategories();
			return;
		}

		VolleyClient.requestCategories(mHomeId, new VolleyListener(this) {

			@Override
			public void onSuccess(String response) {
				Log.d("success request" + response);
				ResultJsonModel jResult = Parse.parseCategoryINews(response);
				if (jResult == null) {
					// error parser
					MyUtil.showDialog("Lỗi server!", IPhimActivity.this);
				} else if (jResult.hasError()) {
					// error register
					String error = jResult.getError();
					MyUtil.showDialog(error, IPhimActivity.this);
				} else {
					mCategories = (List<CategoryModel>) jResult.getResult();
					Map<String, Boolean> catMap = new HashMap<String, Boolean>();
					Iterator<CategoryModel> ite = mCategories.iterator();
					CategoryModel category;
					while (ite.hasNext()) {
						category = ite.next();
						if (catMap.get(category.getRemoteId()) == null) {
							catMap.put(category.getRemoteId(), true);
						} else {
							ite.remove();
						}
					}
					saveCategoriesToDB();
					showCategories();
				}
			}

			@Override
			public void onStart() {
				Log.d("start request");
				showLoading(true);
			}

			@Override
			public void onFinish() {
				Log.d("finish request");
				showLoading(false);
			}

			@Override
			public void onError(VolleyError error) {
				error.printStackTrace();
				MyUtil.showDialog("Lỗi server" + " (" + error.getMessage()
						+ ")", IPhimActivity.this);
			}
		});
	}

	private void saveCategoriesToDB() {

	}

	private void showCategories() {
		mSizeCategories = mCategories.size();
		for (CategoryModel category : mCategories) {
			mFilmCommonModel = new FilmCommonModel();
			mFilmCommonModel.setCategory(category);
			mFilmCommonModel.setMovieModels(new ArrayList<MovieModel>());
			mFilmCommonModels.add(mFilmCommonModel);
			requestListHot(category.getRemoteId());
		}
		mAdapter = new FilmCommonAdapter(this, 0, mFilmCommonModels, this, this);
		mFilmListView.setAdapter(mAdapter);
		mFilmListView.setOnScrollListener(mScrollingListener);
	}

	private void requestListHot(final String categoryId) {

		VolleyClient.requestListHot(mHomeId, categoryId, new VolleyListener(
				this) {

			@Override
			public void onSuccess(String response) {
				Log.d("success request" + response);
				ResultJsonModel jResult = Parse.parseMovieListHot(response);
				if (jResult == null) {
					Log.e("Lỗi lấy list hot từ category " + categoryId);
					mFilmListView.removeHeaderView(mSlideLayout);
				} else if (jResult.hasError()) {
					Log.e(jResult.getError());
					mFilmListView.removeHeaderView(mSlideLayout);
				} else {
					// Save categories to database
					List<MovieModel> movieHots = (List<MovieModel>) jResult
							.getResult();
					saveListHotToDB(movieHots, categoryId);
					showListHot(movieHots, categoryId);
					getMostMovieHot(movieHots, categoryId);
				}
			}

			@Override
			public void onStart() {
				Log.d("start request list hot for category " + categoryId);
			}

			@Override
			public void onFinish() {
				Log.d("finish request list hot for category " + categoryId);
				mIteCategories++;
				Log.d("category " + mIteCategories + " from " + categoryId);
			}

			@Override
			public void onError(VolleyError error) {
				Log.e(error.getMessage());
			}
		});
	}

	private void saveListHotToDB(List<MovieModel> movies, String categoryId) {

	}

	/**
	 * Show list hot of category
	 * 
	 * @param movies
	 * @param categoryId
	 */
	private void showListHot(List<MovieModel> movies, String categoryId) {
		for (FilmCommonModel filmCommon : mFilmCommonModels) {
			if (filmCommon.getCategory().getRemoteId().equals(categoryId)) {
				filmCommon.setMovieModels(movies);
				break;
			}
		}
		mAdapter = new FilmCommonAdapter(this, 0, mFilmCommonModels, this, this);
		mFilmListView.setAdapter(mAdapter);
	}

	/**
	 * Show list hot of iphim or iclip
	 * 
	 * @param movies
	 */
	private void showListHot(List<MovieModel> movies) {
		if (movies == null || movies.size() == 0) {
			mFilmListView.removeHeaderView(mSlideLayout);
			return;
		}
		if (movies.size() == 1) {
			mIndicators.setVisibility(View.GONE);
		}
		// list hot of iclip or iphim
		List<SlideObject> objects = new ArrayList<SlideObject>();
		SlideObject object;
		for (MovieModel movie : movies) {
			object = movie;
			objects.add(object);
		}
		mSlideAdapters = new SlideImagesAdapter(this, objects, onSlideListener);
		mSlideImages = (ViewPager) mSlideLayout.findViewById(R.id.slide_images);
		mSlideImages.setAdapter(mSlideAdapters);
		mIndicators.attachToViewPager(mSlideImages, new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					mSlideMenu
							.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
					break;
				default:
					mSlideMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
					break;
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	private synchronized void getMostMovieHot(List<MovieModel> movies,
			String categoryId) {
		// get 3 movies most views
		for (MovieModel movie : movies) {
			if (!contains(mMovieHots, movie)) {
				mMovieHots.add(movie);
			}
		}
		Collections.sort(mMovieHots, movieCom);
		while (mMovieHots.size() > NUM_MOVIE_HOTS) {
			mMovieHots.remove(mMovieHots.size() - 1);
		}
		if (mIteCategories == mSizeCategories) {
			// finish request list hot of categories
			showListHot(mMovieHots);
		}
	}

	/**
	 * Check movie list containts movie object
	 * 
	 * @param movies
	 * @param movieSelect
	 * @return
	 */
	private boolean contains(List<MovieModel> movies, MovieModel movieSelect) {
		String movieSelectId = movieSelect.getId();
		for (MovieModel movie : movies) {
			if (movie.getId().equals(movieSelectId)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Start video detail activity
	 */
	@Override
	public void onClick(MovieModel movie) {

		Bundle bundle = new Bundle();
		bundle.putSerializable("movie", movie);
		bundle.putString("home_id", mHomeId);
		LaunchIntent.start(IPhimActivity.this, IPhimDetailActivity.class,
				bundle);
	}

	/**
	 * Start iphim category activity
	 */
	@Override
	public void onSelect(CategoryModel category) {
		Bundle bundle = new Bundle();
		bundle.putSerializable("category", category);
		bundle.putString("home_id", mHomeId);
		// if (category.hasGroup() == 1) {
		// LaunchIntent.start(IPhimActivity.this, IPhimTypeActivity.class,
		// bundle);
		// } else {
		// LaunchIntent.start(IPhimActivity.this, IPhimCategoryActivity.class,
		// bundle);
		// }
		LaunchIntent.start(IPhimActivity.this, IPhimCategoryActivity.class,
				bundle);
	}

	/**
	 * 
	 * @return type phim or video
	 */
	public String getHomeId() {
		return mHomeId;
	}

	@Override
	public void setTagMenu() {
		if (mHomeId.equals(AppConstants.ID_IPHIM)) {
			mTagMenu = AppConstants.MENU_IPHIM;
		} else {
			mTagMenu = AppConstants.MENU_ICLIP;
		}
	}

	private Comparator<MovieModel> movieCom = new Comparator<MovieModel>() {
		@Override
		public int compare(final MovieModel object1, final MovieModel object2) {
			return Integer.valueOf(object2.getNumView()).compareTo(
					Integer.valueOf(object1.getNumView()));
		}
	};
}
